package k8s_ui

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"github.com/wonderivan/logger"
	"io"
	"k8s-platform/config"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var Pod pod

type pod struct{}

// 定义列表的返回内容
type PodListDTO struct {
	Items []corev1.Pod `json:"items"`
	Total int          `json:"total"`
}

// 获取pod列表，支持过滤、排序、分页
func (p *pod) GetPods(filterName, namespace string, limit, page int) (podListDto *PodListDTO, err error) {
	//通过clientset获取pod列表
	podList, err := K8s.ClientSet.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		logger.Error("获取Pod列表失败," + err.Error())
		return nil, errors.New("获取Pod列表失败," + err.Error())
	}
	//实例化dataSelector对象
	selectableData := &DataSelector{
		GenericDataList: p.toCells(podList.Items),
		DataSelect: &DataSelectQuery{
			Filter: &FilterQuery{Name: filterName},
			Paginate: &PaginateQuery{
				Limit: limit,
				Page:  page,
			},
		},
	}
	//先过滤
	filtered := selectableData.Filter()
	total := len(filtered.GenericDataList)
	//再去排序和分页
	data := filtered.Sort().Paginate()
	pods := p.fromCells(data.GenericDataList)

	return &PodListDTO{
		Items: pods,
		Total: total,
	}, nil
}

// toCells方法用于将pod类型转成DataCell类型
func (p *pod) toCells(std []corev1.Pod) []DataCell {
	// make([]DataCell, len(std)) 创建一个make函数长度为[]corev1.Pod数量与[]DataCell切片类型
	cells := make([]DataCell, len(std))
	//循环[]corev1.Pod数量(std)
	for i := range std {
		//std[i]原生pod类型 -> podCell -> DataCell
		//将[]corev1.Pod转换成podCell(service.podCell)
		cells[i] = podCell(std[i])
	}
	return cells
}

// fromCells方法用于将DataCell类型转成pod类型
func (p *pod) fromCells(cells []DataCell) []corev1.Pod {
	pods := make([]corev1.Pod, len(cells))
	for i := range cells {
		//cells[i] DataCell接口类型 -> podCell -> 原生pod类型
		pods[i] = corev1.Pod(cells[i].(podCell))
	}
	return pods
}

// 获取pod详情
func (p *pod) GetPodDetail(podName, namespace string) (pod *corev1.Pod, err error) {
	pod, err = K8s.ClientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{})
	if err != nil {
		logger.Error("获取Pod详情失败," + err.Error())
		return nil, errors.New("获取Pod详情失败," + err.Error())
	}
	return pod, nil
}

// 删除pod
func (p *pod) DeletePod(podName, namespace string) (err error) {
	err = K8s.ClientSet.CoreV1().Pods(namespace).Delete(context.TODO(), podName, metav1.DeleteOptions{})
	if err != nil {
		logger.Error("删除Pod失败," + err.Error())
		return errors.New("删除Pod失败," + err.Error())
	}
	return nil
}

// 更新pod
func (p *pod) UpdatePod(podName, namespace, content string) (err error) {
	var pod = &corev1.Pod{}
	//反序列化成pod对象
	err = json.Unmarshal([]byte(content), pod)
	if err != nil {
		logger.Error("反序列化失败," + err.Error())
		return errors.New("反序列化失败," + err.Error())
	}
	//更新pod
	_, err = K8s.ClientSet.CoreV1().Pods(namespace).Update(context.TODO(), pod, metav1.UpdateOptions{})
	if err != nil {
		logger.Error("更新Pod失败," + err.Error())
		return errors.New("更新Pod失败," + err.Error())
	}
	return nil
}

// 辅助能力
// 日志，终端 -> 容器, 并不是pod的维度
// 获取pod中的容器名
func (p *pod) GetPodContainer(podName, namespace string) (containers []string, err error) {
	containers = []string{}
	//获取容器详情
	pod, err := p.GetPodDetail(podName, namespace)
	if err != nil {
		return nil, err
	}
	//从pod对象种获取容器名
	for _, container := range pod.Spec.Containers {
		containers = append(containers, container.Name)
	}
	return containers, nil
}

// 获取容器日志
func (p *pod) GetContainerLog(containerName, podName, namespace string) (log string, err error) {
	//设置日志的配置，容器名，tail的行数
	lineLimit := int64(config.ContainerLogTailLine)
	option := &corev1.PodLogOptions{
		Container: containerName,
		TailLines: &lineLimit,
	}
	//获取request实例
	req := K8s.ClientSet.CoreV1().Pods(namespace).GetLogs(podName, option)
	//发起请求，返回日志内容
	podLogs, err := req.Stream(context.TODO())
	if err != nil {
		logger.Error("获取日志失败," + err.Error())
		return "", errors.New("获取日志失败," + err.Error())
	}
	defer podLogs.Close()
	//写入缓冲区，转成string
	buf := new(bytes.Buffer)
	_, err = io.Copy(buf, podLogs)
	if err != nil {
		logger.Error("写入缓冲区失败," + err.Error())
		return "", errors.New("写入缓冲区失败," + err.Error())
	}

	return buf.String(), nil
}

// 定义每个namespace中pod的数量
type PodNs struct {
	Namespace string `json:"namespace"`
	PodNum    int    `json:"pod_num"`
}

// 获取每个namespace下pod的数量
func (*pod) GetPodNumPerNs() (podNss []*PodNs, err error) {
	podNss = []*PodNs{}
	//获取namespace列表
	namespaceList, err := K8s.ClientSet.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		logger.Error("获取Namespace列表失败," + err.Error())
		return nil, errors.New("获取Namespace列表失败," + err.Error())
	}
	for _, namespace := range namespaceList.Items {
		podList, err := K8s.ClientSet.CoreV1().Pods(namespace.Name).List(context.TODO(), metav1.ListOptions{})
		if err != nil {
			logger.Error("获取Pod列表失败," + err.Error())
			return nil, errors.New("获取Pod列表失败," + err.Error())
		}
		podNss = append(podNss, &PodNs{
			Namespace: namespace.Name,
			PodNum:    len(podList.Items),
		})
	}
	return podNss, nil
}
